'use strict';

const mongoose = require('mongoose'),
    foodModel = mongoose.model('Food');

module.exports = {
    addFood: addFood,
    deleteFood: deleteFood,
    updateFood: updateFood,  
    getFoodByFname: getFoodByFname, 
    getFoodByIcnum: getFoodByIcnum,
    getFoodByFtype: getFoodByFtype,
    getFoodByIcnumFtype: getFoodByIcnumFtype,
    getFoodById : getFoodById,
}



function addFood(food,files,callback){
    var fpic  = files.FoodImage;
    if(fpic.originalFilename!=''){
        var fs = require('fs');
      var fpicname = parseInt(Math.random()*10000000)+fpic.name;
      var fpicpath = "D://img/food/"+fpicname; 
      var fpicSrcPath = "http://10.222.29.187:8089/pic/food/"+fpicname;
      food.fimg = fpicSrcPath;
       fs.rename(fpic.path,fpicpath);
    }

    foodModel.create(food,function(error,data){
        callback(null,data);
    });
}

function deleteFood(_id,callback){
    foodModel.remove({'_id':_id},function(error,data){
        callback(null,data);
    });
}



function updateFood(food,files,callback){
    var f ={}; 
    var fpic  = files.FoodImage;
    if(fpic.originalFilename!=''){
        var fs = require('fs');
      var fpicname = parseInt(Math.random()*10000000)+fpic.name;
      var fpicpath = "D://img/food/"+fpicname; 
      var fpicSrcPath = "http://10.222.29.187:8089/pic/food/"+fpicname;
      f.fimg = fpicSrcPath;
       fs.rename(fpic.path,fpicpath);
    }

      f.fname= food.fname;
      f.fprice= food.fprice;
      f.ftype=food.ftype;
    foodModel.update({'_id':food._id},f,function(error,data){
        callback(null,data);
    });
}

function getFoodByFname(fname,callback){
    foodModel.find({'fname':fname},function(error,data){
        callback(null,data);
    });
}

function getFoodByFtype(ftype,callback){
    foodModel.find({'ftype':ftype},function(error,data){
        callback(null,data);
    });
}

function getFoodByIcnum(icnum,callback){
    foodModel.find({'merchantIcnum':icnum},function(error,data){
        callback(null,data);
    });
}

function getFoodByIcnumFtype(icnum,ftype,callback){
    foodModel.find({
        merchantIcnum : icnum,
        ftype : ftype
        },function(error,data){
        callback(null,data);
    });
}

function getFoodById(_id,callback){
    foodModel.findOne({'_id':_id},function(error,data){
        callback(null,data);
    });

}